﻿using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web.Configuration;
using System.Web.Security;
using System.Security.Cryptography;
using System.IO;
using System.Web;
using lcomixcore;

namespace comix
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>

    public class dn : IHttpHandler
    {

        const int CHUNCSIZE = 20000;

        public void ProcessRequest(HttpContext context)
        {
            int n = 0;
            string s = "";
            try
            {
                StreamReader sr1 = new StreamReader(context.Request.InputStream);
                s = sr1.ReadToEnd();
                Dictionary<string,int> parameters = new Dictionary<string, int>();
                char[] sep = { '&' };
                char[] sep1 = { '=' };
                string[] parts = s.Split(sep);
                foreach (string p in parts)
                {
                    string[] subparts = p.Split(sep1);
                    if (subparts.Length == 2)
                        parameters.Add(subparts[0], Convert.ToInt32(subparts[1]));
                }
                n = 1;
                int userid = parameters["usrid"];
                int bokid = parameters["bokid"];

                n = 2;
                SqlConnection con = new SqlConnection();
                con.ConnectionString = WebConfigurationManager.ConnectionStrings["mainconectionstring"].ConnectionString;
                SqlCommand com = new SqlCommand();
                com.Connection = con;
                com.CommandText = "SELECT usr_code, u2b_issample FROM BOOKS2USERS INNER JOIN USERS on usr_id = u2b_usr_id WHERE usr_id = @usrid AND u2b_bok_id = @bokid";
                com.Parameters.Add(new SqlParameter("@usrid", userid));
                com.Parameters.Add(new SqlParameter("@bokid", bokid));
                con.Open();
                string code = "";
                string file = bokid.ToString() + ".cmk";
                string demo = "s" + file;
                bool issample = false;

                SqlDataReader rdr = com.ExecuteReader();
                if (rdr.Read())
                {
                    code = rdr.GetString(0);
                    issample = rdr.GetBoolean(1);
                }
                else
                    file = "";
                con.Close();

                n = 3;

                if (file != "")
                {
                    byte[] b;
                    if (issample)
                    {                        
                        string path = context.Request.MapPath("books/" + demo);
                        b = File.ReadAllBytes(path);
                        context.Response.OutputStream.Write(b, 0, b.Length);
                    }
                    else
                    {
                        n = 4;
                        MD5 md5 = MD5.Create();
                        byte[] mdmkey = md5.ComputeHash(System.Text.Encoding.ASCII.GetBytes(code));
                        byte[] thesecretkey = { 45, 17, 190, 200, 1, 67, 139, 127, 68, 100, 103, 217, 11, 89, 92, 237 };
                        Rijndael rij = Rijndael.Create();
                        rij.Mode = CipherMode.CBC;
                        rij.Padding = PaddingMode.None;
                        byte[] iv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                        byte[] ivv = { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 };
                        MemoryStream ms = new MemoryStream();
                        CryptoStream crypt = new CryptoStream(ms, rij.CreateEncryptor(thesecretkey, iv), CryptoStreamMode.Write);
                        crypt.Write(mdmkey, 0, mdmkey.Length);
                        crypt.Close();
                        byte[] encoded = ms.ToArray();
                        string finalpassword = Convert.ToBase64String(encoded);

                        n = 5;
                        string path = context.Request.MapPath("books/" + file);
                        lBook book = new lBook();
                        book.Open(path);
                     //   ikbmanager.ikbmanager manager = new ikbmanager.ikbmanager();
                     //   manager.Load(path);
                        n = 6;
                        MemoryStream msf = new MemoryStream();
                        book.Save(msf, encoded);
                        //manager.Save(msf, encoded);
                        byte[] res = msf.ToArray();
                        msf.Close();
                        context.Response.OutputStream.Write(res, 0, res.Length);


                       
                
                    }
                }
            }
            catch (Exception e)
            {
                context.Response.Write("ERR " + n.ToString()+" "+s+" " + e.Message);
            }
            context.Response.End();
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
